<template>
  <div class="el-amap-content">
    <el-select
      v-model="selectAddress"
      filterable
      remote
      reserve-keyword
      :placeholder="`请选择${placeholder}`"
      :remote-method="autoInput"
      clearable
      @change="handleChange"
      :style="{ marginBottom: '10px', ...inputStyle }"
    >
      <el-option
        v-for="(item, index) in selectOptions"
        :key="index"
        :label="item.name"
        :value="item.name"
        :loading="loading"
      >
      </el-option>
    </el-select>
    <el-amap
      vid="amapDemo"
      class="amap-container"
      :amap-manager="amapManager"
      :zoom="13"
      :center="center"
      :events="events"
    >
      <el-amap-marker :position="center"></el-amap-marker>
      <el-amap-text
        :position="center"
        :text="textCont"
        :offset="textOffset"
      ></el-amap-text>
    </el-amap>
  </div>
</template>
<script>
import { promise } from "@/utils";
import { AMapManager } from "vue-amap";
let amapManager = new AMapManager();

export default {
  props: {
    address: {
      type: [Number, String],
      default: () => "",
    },
    initCenter: {
      type: Array,
      default: () => [],
    },
    getPoit: {
      type: Function,
    },
    inputStyle: {
      type: Object,
      default: () => ({}),
    },
    placeholder: {
      type: String,
      default: () => "",
    },
    areaName: {
      type: String,
      default: () => "",
    },
  },
  data() {
    return {
      map: null,
      potIndex: null,
      initText: "",
      amapManager,
      selectAddress: "",
      center: [0, 0],
      selectText: "",
      loading: true,
      selectOptions: [],
      setTime: null,
      params: {
        enableHighAccuracy: true, //是否使用高精度定位，默认:true
        timeout: 5000, //超过10秒后停止定位，默认：无穷大
        maximumAge: 0, //定位结果缓存0毫秒，默认：0
        convert: false, //自动偏移坐标，偏移后的坐标为高德坐标，默认：true, 如果协议是GCJ-02，需要ios和安卓统一
        showButton: true, //显示定位按钮，默认：true
        buttonPosition: "LB", //定位按钮停靠位置，默认：'LB'，左下角
        showMarker: true, //定位成功后在定位到的位置显示点标记，默认：true
        showCircle: true, //定位成功后用圆圈表示定位精度范围，默认：true
        panToLocation: true, //定位成功后将定位到的位置作为地图中心点，默认：true
        zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        // eslint-disable-next-line no-undef
        // buttonOffset: AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
      },
      textCont: "",
      textOffset: [-2, -54],
      events: {
        complete: () => {
          this.init();
        },
      },
    };
  },
  created() {},
  mounted() {},
  methods: {
    autoInput(e, bol) {
      this.$nextTick(() => {
        if (e.replace(/\s/g, "")) {
          this.loading = true;
          let { AMap } = window;
          if (this.setTime) {
            clearTimeout(this.setTime);
          }
          this.setTime = setTimeout(() => {
            this.map.plugin("AMap.Autocomplete", () => {
              const autoOptions = {
                city: "全国",
              };
              var autoComplete = new AMap.Autocomplete(autoOptions);
              autoComplete.search(`${this.areaName}${e}`, (status, result) => {
                this.selectOptions = result.tips;
                this.loading = false;
                if (bol) {
                  this.handleChange(e);
                }
              });
            });
          }, 1000);
        } else {
          this.selectOptions = [];
        }
      });
    },
    handleChange(e) {
      if (e.replace(/\s/g, "")) {
        let { district, name, location } = this.selectOptions.find(
          (val) => val.name === e
        );
        let { lat, lng } = location;
        this.center = [lng, lat];
        this.textCont = district + name;
        this.selectAddress = name;
        this.getPoit({ lng, lat, address: name });
      } else {
        this.$emit("update:address", e);
      }
    },
    async init() {
      let { AMap } = window;
      let { params, onComplete, onError } = this;
      this.map = new AMap.Map("container", {
        resizeEnable: true,
      });
      this.geocoder = new AMap.Geocoder({});
      this.map.plugin("AMap.Geolocation", () => {
        let geolocation = new AMap.Geolocation(params);
        this.map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, "complete", onComplete); //返回定位信息
        AMap.event.addListener(geolocation, "error", onError); //返回定位出错信息
      });
    },
    onComplete(data) {
      this.initText = "初始化定位完成了";
      let { formattedAddress, position } = data;
      this.textCont = formattedAddress;
      let { lng, lat } = position;
      this.center = [lng, lat];
      this.getPoit({ lng, lat });
      this.autoInput(this.address, true);
    },
    onError() {
      this.$message.error("获取当前位置失败");
      this.autoInput(this.address, true);
    },
    getAddressName(resolve, reject) {
      this.geocoder.getLocation(this.address, (status, result) => {
        if (status === "complete") {
          resolve(result);
        } else {
          reject("查询地址出错");
        }
      });
    },
    getPositionByLonLats(resolve, reject, { center }) {
      this.geocoder.getAddress(center, (status, result) => {
        if (status === "complete" && result.info === "OK") {
          resolve(result);
        } else {
          this.textCont = "";
          reject("获取地址失败");
        }
      });
    },
    async getGeocoder() {
      let result = await promise(this.getAddressName).catch();
      let { location } = result.geocodes[0];
      let { lat, lng } = location;
      this.center = [lng, lat];
      let res = await promise(this.getPositionByLonLats, {
        center: this.center,
      }).catch();
      this.textCont = res.regeocode.formattedAddress;
      this.selectAddress = name;
      this.getPoit({ lng, lat, address: this.textCont });
    },
  },
};
</script>
<style lang="less" scoped>
.amap-container {
  width: 700px;
  height: 300px;
}
</style>
